<?php

namespace App\Http\Controllers\Admin;

use App\Http\Config\ErrorCode;
use App\Library\Tools;
use App\Models\Admin\AdminUser;
use App\Models\Company;
use App\Models\User\UserWechat;
use App\Models\Wechat;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class CompanyController extends BaseController
{
    public function __construct(Request $request){
        parent::__construct($request);
    }

    /* 获取数据列表 */
    public function dataList(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $page_no = $request->post('page_no', 1);
        $page_size = $request->post('page_size', 10);
        $searchFilter = array(
            'sortName' => $request->post('sortName','id'),                                                  //排序列名
            'sortOrder' => $request->post('sortOrder','asc'),                                               //排序（desc，asc）
            'pageNumber' => $page_no,                                                                                   //当前页码
            'pageSize' => $page_size,                                                                                   //一页显示的条数
            'start' => ($page_no-1) * $page_size,                                                                       //开始位置
            'searchKey' => trim($request->post('search',''))                                                //搜索条件
        );
        $companyModel = new Company();
        $res = $companyModel->getCompanyWithFilter($searchFilter);
        $new_array = array();
        try {
            $data = Wechat::getInstance()->departmentList();
            foreach ($data as $key => $value) {
                if (isset($value["id"])) {
                    $new_array[$value['id']] = $value;
                }
            }
        }catch (\Exception $e){}
        foreach ($res['rows'] as &$item){
            $item['departmentName'] = isset($new_array[$item['wechat_channel_id']]) ? $new_array[$item['wechat_channel_id']]['name'] : "";
        }
        $this->returnData['data'] = $res;
        return $this->return_result($this->returnData);
    }

    // 企业微信部门
    public function getDepartmentList(){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        try {
            $data = Wechat::getInstance()->departmentList();
            if ($data) {
                $data = array_values(Tools::array_sort($data, 'parentid'));
            }
        }catch (\Exception $e){
            $data = [];
        }
        $this->returnData['data'] = $data;
        return $this->return_result($this->returnData);
    }

    /* 获取公司列表 */
    public function companyList(){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $columns = ['id','name'];
        $branchModel = new Company();
        $res = $branchModel->getCompanyList($columns);
        if(!$res){
            $this->returnData['msg'] = '暂无数据';
            return $this->return_result($this->returnData);
        }
        $this->returnData['data'] = $res;
        return $this->return_result($this->returnData);
    }

    /* 添加公司 */
    public function create(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $company_name = trim($request->name);
        if(empty($company_name)){
            return ErrorCode::code("params_not_exist", '部门名称');
        }
        $companyModel = new Company();
        $res = $companyModel->getCompanyByName($company_name);
        if(is_array($res)){
            return ErrorCode::code("customized", '部门名称已使用,请重新输入');
        }
        $wechat_channel_id = trim($request->wechat_channel_id);
        if($wechat_channel_id){
            if(!is_numeric($wechat_channel_id))
                return ErrorCode::code("customized", '企业微信部门ID格式错误');
        }else{
            $wechat_channel_id = null;
        }
        $type = trim($request->post('type', 1));
        if(!$type || !in_array($type, [1, 2, 3])){
            return ErrorCode::code("customized", 'type错误');
        }
        if($type == '2'){
            $parent_id = trim($request->parent_id);
            if(empty($parent_id)){
                return ErrorCode::code("params_not_exist", '父部门id');
            }
            $wechat_channel_id = UserWechat::getInstance()->addDepartment($company_name, $parent_id, $msg);
            if(!$wechat_channel_id){
                return ErrorCode::code("customized", $msg);
            }
        }elseif($type == '3'){
            $wechat_channel_id = null;
        }
        if($type == '1' && $wechat_channel_id && Company::query()->where(["mall_id" => $request->mallData['id'], 'wechat_channel_id' => $wechat_channel_id])->count()){
            return ErrorCode::code("customized", '企业微信部门ID已关联');
        }
        $res = $companyModel->companyInsert(['name' => $company_name, 'wechat_channel_id' => $wechat_channel_id]);
        if(!$res){
            $this->returnData = ErrorCode::$admin_enum['fail'];
            $this->returnData['msg'] = '添加失败';
            return $this->return_result($this->returnData);
        }
        $this->returnData['msg'] = '添加成功';
        return $this->return_result($this->returnData);
    }

    /* 修改公司 */
    public function edit(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $id = $request->id;
        $company_name = trim($request->name);
        if(empty($company_name)){
            return ErrorCode::code("params_not_exist", '部门名称');
        }
        $companyModel = new Company();
        if(!$data = $companyModel->getCompanyByID($id)){
            return $this->return_result(ErrorCode::code("customized", "公司不存在"));
        }
        $res = $companyModel->getCompanyByName($company_name,$id);
        if(is_array($res)){
            return ErrorCode::code("customized", '部门名称已使用,请重新输入');
        }
        $wechat_channel_id = trim($request->wechat_channel_id);
        if($wechat_channel_id){
            if(!is_numeric($wechat_channel_id))
                return ErrorCode::code("customized", '企业微信部门ID格式错误');
        }else{
            $wechat_channel_id = null;
        }
        $type = trim($request->post('type', 1));
        if(!$type || !in_array($type, [1, 2, 3])){ // 1 :已有部门；2：同步创建部门；3：不关联
            return ErrorCode::code("customized", 'type错误');
        }
        if($type == '2'){
            $parent_id = trim($request->parent_id);
            if(empty($parent_id)){
                return ErrorCode::code("params_not_exist", '父部门id');
            }
            $wechat_channel_id = UserWechat::getInstance()->addDepartment($company_name, $parent_id, $msg);
            if(!$wechat_channel_id){
                return ErrorCode::code("customized", $msg);
            }
        }elseif($type == '3'){
            $wechat_channel_id = null;
        }
        if($type == '1' && $wechat_channel_id && Company::query()->where(["mall_id" => $request->mallData['id'], 'wechat_channel_id' => $wechat_channel_id])->where("id", "<>", $id)->count()){
            return ErrorCode::code("customized", '企业微信部门ID已关联');
        }
        DB::beginTransaction();
        $res = $companyModel->companyUpdate($id,['name' => $company_name,'wechat_channel_id' => $wechat_channel_id]);
        if(!$res){
            DB::rollBack();
            $this->returnData = ErrorCode::$admin_enum['fail'];
            $this->returnData['msg'] = '修改失败';
            return $this->return_result($this->returnData);
        }
        if($type == '3'){
            $wechat_channel_id = 1;
        }
        if($data['wechat_channel_id'] != $wechat_channel_id && !UserWechat::getInstance()->updateDepartment($id, $wechat_channel_id, $msg)){
            DB::rollBack();
            return $this->return_result(ErrorCode::code("customized", $msg ?: "处理部门成员迁移失败"));
        }
        DB::commit();
        $this->returnData['msg'] = '修改成功';
        return $this->return_result($this->returnData);
    }

    /* 公司删除 */
    public function delete($id){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $companyModel = new Company();
        if(!$data = $companyModel->getCompanyByID($id)){
            return $this->return_result(ErrorCode::code("customized", "公司不存在"));
        }
        $count = AdminUser::query()->from(AdminUser::query()->getModel()->getTable()." as u")
            ->leftJoin(Company::query()->getModel()->getTable()." as c", "u.company_id", "=", "c.id")
            ->where(["c.id" => $id, "u.mall_id" => request()->mallData['id']])
            ->count();
        if($count){
            return $this->return_result(ErrorCode::code("customized", "系统部门下有成员"));
        }
        if($data['wechat_channel_id']) {
            if(!UserWechat::getInstance()->delDepartment($data['wechat_channel_id'], $msg)){
                return $this->return_result(ErrorCode::code("customized", $msg));
            }
        }
        $res = $companyModel->companyDelete($id);
        if(!$res){
            $this->returnData = ErrorCode::$admin_enum['fail'];
            $this->returnData['msg'] = '删除失败';
            return $this->return_result($this->returnData);
        }
        $this->returnData['msg'] = '删除成功';
        return $this->return_result($this->returnData);
    }
}
